import * as step from '@ali/flow-step-toolkit'
import {GetObjectResult, PutObjectOptions, PutObjectResult, Option, RemoteStorage} from './storage'
import OSS from 'ali-oss'
import path from 'path';

export class OSSStorage implements RemoteStorage {
    private ossClient: OSS;

    constructor(option: Option) {
        this.ossClient = new OSS({
            accessKeyId: option.accessKeyID,
            accessKeySecret: option.accessKeySecret,
            stsToken: option.securityToken,
            refreshSTSTokenInterval: 1000 * 3600, // for remove log: It's recommended to set 'refreshSTSToken' and 'refreshSTSTokenInterval' to refresh stsToken、accessKeyId、accessKeySecret automatically when sts token has expired
            bucket: option.bucket,
            endpoint: option.endpoint
        });
    }

    async stat(objectKey: string): Promise<boolean> {
        try {
            await this.ossClient.head(objectKey);
            return Promise.resolve(true);
        } catch (error) {
            // @ts-ignore
            step.warnV1(`error status ${error.status} name ${error.name} message ${error.message}`)
            return Promise.resolve(false);
        }
    }

    async put(objectKey: string, filePath: string, options?: PutObjectOptions): Promise<PutObjectResult> {
        // local filePath -> oss objectKey
        return this.ossClient.put(objectKey, path.normalize(filePath), options);
    }

    async get(objectKey: string, filePath: string): Promise<GetObjectResult> {
        // oss objectKey -> local filePath
        return this.ossClient.get(objectKey, path.normalize(filePath));
    }
}